// 全局变量存储错题数据
let errorQuestions = [];
// 当前选中的题目ID
let currentQuestionId = null;

// DOM元素
const questionList = document.getElementById('questionList');
const questionsCount = document.getElementById('questionsCount');
const questionDetailModal = document.getElementById('questionDetailModal');
const modalQuestionTitle = document.getElementById('modalQuestionTitle');
const modalQuestionContent = document.getElementById('modalQuestionContent');
const closeDetailModal = document.getElementById('closeDetailModal');
const closeModalBtn = document.getElementById('closeModalBtn');
const redoQuestionBtn = document.getElementById('redoQuestionBtn');
const applyFilter = document.getElementById('applyFilter');
const resetFilter = document.getElementById('resetFilter');
// 生成试卷相关元素
const generatePaperBtn = document.getElementById('generatePaperBtn');
const generatePaperModal = document.getElementById('generatePaperModal');
const closePaperModal = document.getElementById('closePaperModal');
const cancelPaperBtn = document.getElementById('cancelPaperBtn');
const confirmPaperBtn = document.getElementById('confirmPaperBtn');
const releaseTimeInput = document.getElementById('releaseTime');
const examDurationInput = document.getElementById('examDuration');
const paperQuestionCount = document.getElementById('paperQuestionCount');

// 等待弹窗相关元素
let waitingModal = null;

// 初始化页面
function initPage() {
    fetchErrorQuestions();
    bindEvents();
    // 初始化弹窗事件
    initModalEvents();
    // 初始化生成试卷相关
    initGeneratePaper();
    // 初始化等待弹窗
    initWaitingModal();
}

// 从后端接口获取错题数据
function fetchErrorQuestions() {
    fetch('/errornote/select', {
        method: 'GET',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/json',
        }
    })
        .then(response => {
            if (!response.ok) {
                throw new Error(`请求失败: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('后端返回原始数据:', data);

            if (data && data.data && Array.isArray(data.data)) {
                errorQuestions = data.data;
                errorQuestions.forEach(question => {
                    if (question.createTime && typeof question.createTime === 'string') {
                        question.createTime = new Date(question.createTime).toISOString();
                    }
                });
                renderQuestionList(errorQuestions);
                // 更新试卷题目数量
                updatePaperQuestionCount();
            } else {
                questionList.innerHTML = '<div class="empty-state">数据格式错误：未找到有效错题数据</div>';
                questionsCount.textContent = '共 0 道错题';
                updatePaperQuestionCount();
            }
        })
        .catch(error => {
            console.error('获取错题失败:', error);
            questionList.innerHTML = `<div class="empty-state">加载失败: ${error.message}</div>`;
            questionsCount.textContent = '共 0 道错题';
            showAlertModal("提示", `获取错题失败: ${error.message}`);
            updatePaperQuestionCount();
        });
}

// 渲染错题列表
function renderQuestionList(questions) {
    questionList.innerHTML = '';

    if (questions.length === 0) {
        questionList.innerHTML = '<div class="empty-state">没有找到错题记录</div>';
        questionsCount.textContent = '共 0 道错题';
        updatePaperQuestionCount();
        return;
    }

    questions.forEach((question) => {
        const questionCard = document.createElement('div');
        questionCard.className = 'question-card';
        questionCard.dataset.questionId = question.id;

        questionCard.innerHTML = `
            <div class="question-card-header">
                <div class="question-card-title">${question.question}</div>
                <div class="question-card-meta">
                    <span>题型: ${question.questionType || '未知'}</span>
                    <span>考试名称: ${question.examName || '未知'}</span>
                    <span>添加时间: ${formatDate(question.createTime)}</span>
                </div>
            </div>
            <div class="question-card-content">
                ${question.options ? `选项: ${formatOptions(question.options)}` : ''}
            </div>
            <div class="question-card-footer">
                <div class="answer-info">
                    <span class="your-answer">你的答案: ${question.answer || '<span style="color:var(--text-light);font-style:italic">未作答</span>'}</span>
                    <span class="correct-answer">正确答案: ${question.correctAnswer || '无'}</span>
                </div>
                ${question.reason ? `<div class="question-card-status">错误原因: ${question.reason}</div>` : ''}
            </div>
        `;

        questionCard.addEventListener('click', () => showQuestionDetail(question.id));
        questionList.appendChild(questionCard);
    });

    questionsCount.textContent = `共 ${questions.length} 道错题`;
    updatePaperQuestionCount();
}

// 显示错题详情
function showQuestionDetail(questionId) {
    const question = errorQuestions.find(q => q.id === questionId);
    if (!question) return;

    currentQuestionId = questionId;
    modalQuestionTitle.textContent = question.question;

    let optionsHtml = '';
    if (question.options) {
        optionsHtml = `
            <div class="detail-section">
                <h4 class="detail-title">选项</h4>
                <div class="detail-content">${formatOptions(question.options)}</div>
            </div>
        `;
    }

    modalQuestionContent.innerHTML = `
        <div class="detail-section">
            <h4 class="detail-title">题目内容</h4>
            <div class="detail-content">${question.question}</div>
        </div>
        
        ${optionsHtml}
        
        <div class="detail-section">
            <h4 class="detail-title">你的答案</h4>
            <div class="detail-content ${!question.answer ? 'empty' : ''}">
                ${question.answer || '未作答'}
            </div>
        </div>
        
        <div class="detail-section">
            <h4 class="detail-title">正确答案</h4>
            <div class="detail-content">${question.correctAnswer || '无'}</div>
        </div>
        
        <div class="detail-section">
            <h4 class="detail-title">错误原因</h4>
            <div class="detail-content">${question.reason || '无'}</div>
        </div>
        
        <div class="detail-section">
            <h4 class="detail-title">题目信息</h4>
            <div class="detail-content">
                <p>题型: ${question.questionType || '未知'}</p>
                <p>考试名称: ${question.examName || '未知'}</p>
                <p>添加时间: ${formatDate(question.createTime)}</p>
            </div>
        </div>
    `;

    questionDetailModal.classList.add('show');
}

// 格式化选项显示
function formatOptions(options) {
    if (!options) return '';
    return options.split(';').map(option => `<div>${option}</div>`).join('');
}

// 格式化日期显示
function formatDate(dateString) {
    if (!dateString) return '未知时间';
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return '无效时间';

    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}

// 关闭详情弹窗
function closeModal() {
    questionDetailModal.classList.remove('show');
    currentQuestionId = null;
}

// 删除错题
function deleteQuestion() {
    if (currentQuestionId === null) return;

    const question = errorQuestions.find(q => q.id === currentQuestionId);
    if (!question || !question.id) {
        showAlertModal("提示", "无法获取题目信息，删除失败");
        return;
    }

    showConfirmModal("确认删除", "确定要将这道题从错题本中删除吗？", () => {
        const formData = new FormData();
        formData.append('id', question.id);
        console.log('发送的删除id:', question.id);

        fetch('/errornote/delete', {
            method: 'POST',
            credentials: 'include',
            body: formData
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`网络请求失败: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('后端返回数据:', data);

                if (data && data.code === "0000") {
                    errorQuestions = errorQuestions.filter(q => q.id !== currentQuestionId);
                    closeModal();
                    applyFilters();
                    showAlertModal("提示", data.msg || "错题已成功删除");
                } else {
                    throw new Error(data?.msg || '删除失败，后端返回异常');
                }
            })
            .catch(error => {
                console.error('删除错题失败:', error);
                showAlertModal("提示", `删除失败：${error.message}`);
            });
    });
}

// 应用筛选
function applyFilters() {
    const questionType = document.getElementById('questionType').value;
    const timeRange = document.getElementById('timeRange').value;
    const sortOrder = document.getElementById('sortOrder').value;

    let filteredQuestions = [...errorQuestions];

    // 按题型筛选
    if (questionType !== 'all') {
        filteredQuestions = filteredQuestions.filter(q => q.questionType === questionType);
    }

    // 按时间范围筛选
    if (timeRange !== 'all') {
        const now = new Date();
        let days = 0;

        switch(timeRange) {
            case 'week': days = 7; break;
            case 'month': days = 30; break;
            case 'quarter': days = 90; break;
            case 'halfyear': days = 180; break;
            case 'year': days = 365; break;
            default: days = 0;
        }

        const startTime = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
        filteredQuestions = filteredQuestions.filter(q => {
            if (!q.createTime) return false;
            const questionTime = new Date(q.createTime);
            return !isNaN(questionTime.getTime()) && questionTime >= startTime;
        });
    }

    // 按时间排序
    filteredQuestions.sort((a, b) => {
        if (!a.createTime || !b.createTime) return 0;
        const timeA = new Date(a.createTime).getTime();
        const timeB = new Date(b.createTime).getTime();
        return sortOrder === 'time_asc' ? timeA - timeB : timeB - timeA;
    });

    renderQuestionList(filteredQuestions);
}

// 重置筛选
function resetFilters() {
    document.getElementById('questionType').value = 'all';
    document.getElementById('timeRange').value = 'all';
    document.getElementById('sortOrder').value = 'time_asc';
    renderQuestionList(errorQuestions);
}

// 初始化弹窗事件
function initModalEvents() {
    $('.close-modal').click(function() {
        $(this).closest('.modal').removeClass('show');
    });

    $(document).click(function(e) {
        if ($(e.target).hasClass('modal')) {
            $(e.target).removeClass('show');
        }
    });
}

// 显示提示弹窗
function showAlertModal(title, message, callback) {
    const modal = $('#alertModal');
    $('#alertTitle').text(title);
    $('#alertMessage').text(message);
    modal.addClass('show');

    const confirmBtn = $('#confirmAlertBtn');
    confirmBtn.off('click');

    confirmBtn.click(function() {
        modal.removeClass('show');
        if (typeof callback === 'function') {
            callback();
        }
    });
}

// 显示确认弹窗
function showConfirmModal(title, message, confirmCallback, cancelCallback) {
    const modal = $('#confirmModal');
    $('#confirmTitle').text(title);
    $('#confirmMessage').text(message);
    modal.addClass('show');

    const confirmBtn = $('#confirmActionBtn');
    const cancelBtn = $('#cancelActionBtn');
    confirmBtn.off('click');
    cancelBtn.off('click');

    confirmBtn.click(function() {
        modal.removeClass('show');
        if (typeof confirmCallback === 'function') {
            confirmCallback();
        }
    });

    cancelBtn.click(function() {
        modal.removeClass('show');
        if (typeof cancelCallback === 'function') {
            cancelCallback();
        }
    });
}

// 绑定事件
function bindEvents() {
    closeDetailModal?.addEventListener('click', closeModal);
    closeModalBtn?.addEventListener('click', closeModal);
    redoQuestionBtn?.addEventListener('click', deleteQuestion);
    applyFilter?.addEventListener('click', applyFilters);
    resetFilter?.addEventListener('click', resetFilters);

    questionDetailModal?.addEventListener('click', (e) => {
        if (e.target === questionDetailModal) {
            closeModal();
        }
    });

    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && questionDetailModal?.classList.contains('show')) {
            closeModal();
        }
    });
}

// 初始化生成试卷功能
function initGeneratePaper() {
    // 设置默认发布时间为当前时间后30分钟
    const defaultTime = new Date();
    defaultTime.setMinutes(defaultTime.getMinutes() + 30);
    releaseTimeInput.value = defaultTime.toISOString().slice(0, 16);

    // 绑定生成试卷按钮事件
    generatePaperBtn?.addEventListener('click', openGeneratePaperModal);

    // 绑定关闭和取消按钮事件
    closePaperModal?.addEventListener('click', closeGeneratePaperModal);
    cancelPaperBtn?.addEventListener('click', closeGeneratePaperModal);

    // 绑定确认生成按钮事件（整合所有逻辑）
    confirmPaperBtn?.addEventListener('click', function() {
        // 显示等待弹窗
        showWaitingModal();

        // 隐藏生成试卷弹窗
        generatePaperModal.classList.remove('show');

        const releaseTime = releaseTimeInput.value;
        const examDuration = examDurationInput.value;

        // 验证输入
        if (!releaseTime) {
            hideWaitingModal();
            showAlertModal('提示', '请选择考试发布时间');
            return;
        }

        if (!examDuration || examDuration < 10 || examDuration > 180) {
            hideWaitingModal();
            showAlertModal('提示', '请输入10-180之间的考试时长');
            return;
        }

        // 获取当前可见的题目
        const visibleQuestions = getVisibleQuestions();
        if (visibleQuestions.length === 0) {
            hideWaitingModal();
            showAlertModal('提示', '没有符合条件的错题可生成试卷');
            return;
        }

        // 构建题目字符串（使用换行分隔）
        const questions = visibleQuestions.map(item => item.question).join('\n');

        // 构建请求数据
        const requestData = {
            questions: questions,
            release_time: releaseTime,
            exam_duration: parseInt(examDuration)
        };
        console.log("requestData.questions:-------"+requestData.questions)
        console.log("requestData.release_time:-------"+requestData.release_time)
        console.log("requestData.exam_duration:-------"+requestData.exam_duration)

        // 发送请求到后端
        fetch('/errornote/insert', {  // 请替换为实际后端接口
            method: 'POST',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(requestData)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`请求失败: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('生成试卷成功:', data);
                hideWaitingModal();
                if (data && data.code === "0000") {
                    showAlertModal('成功', data.msg || '试卷生成成功！');
                } else {
                    showAlertModal('提示', data?.msg || '试卷生成失败，请重试');
                }
            })
            .catch(error => {
                console.error('生成试卷失败:', error);
                hideWaitingModal();
                showAlertModal('错误', `生成试卷失败: ${error.message}`);
            });
    });
}

// 打开生成试卷弹窗
function openGeneratePaperModal() {
    updatePaperQuestionCount();
    generatePaperModal.classList.add('show');
}

// 关闭生成试卷弹窗
function closeGeneratePaperModal() {
    generatePaperModal.classList.remove('show');
}

// 更新试卷中的题目数量
function updatePaperQuestionCount() {
    // 获取当前筛选后的题目数量
    const visibleQuestions = getVisibleQuestions();
    paperQuestionCount.textContent = visibleQuestions.length;
}

// 获取当前可见的题目（考虑筛选条件）
function getVisibleQuestions() {
    const questionType = document.getElementById('questionType').value;
    const timeRange = document.getElementById('timeRange').value;

    let filteredQuestions = [...errorQuestions];

    // 应用当前筛选条件
    if (questionType !== 'all') {
        filteredQuestions = filteredQuestions.filter(q => q.questionType === questionType);
    }

    if (timeRange !== 'all') {
        const now = new Date();
        let days = 0;

        switch(timeRange) {
            case 'week': days = 7; break;
            case 'month': days = 30; break;
            case 'quarter': days = 90; break;
            case 'halfyear': days = 180; break;
            case 'year': days = 365; break;
            default: days = 0;
        }

        const startTime = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
        filteredQuestions = filteredQuestions.filter(q => {
            if (!q.createTime) return false;
            const questionTime = new Date(q.createTime);
            return !isNaN(questionTime.getTime()) && questionTime >= startTime;
        });
    }

    return filteredQuestions;
}

// 初始化等待弹窗
function initWaitingModal() {
    // 创建等待弹窗元素
    waitingModal = document.createElement('div');
    waitingModal.id = 'waitingModal';
    waitingModal.className = 'modal';
    waitingModal.innerHTML = `
        <div class="modal-content" style="max-width: 400px;">
            <div class="modal-header">
                <h3>处理中</h3>
            </div>
            <div class="modal-body" style="text-align: center; padding: 2rem 1.5rem;">
                <div style="margin-bottom: 1rem;">
                    <svg width="50" height="50" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <circle cx="12" cy="12" r="10" stroke="#3b82f6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="100" stroke-dashoffset="0">
                            <animate attributeName="stroke-dashoffset" from="0" to="100" dur="1.5s" repeatCount="indefinite" />
                        </circle>
                    </svg>
                </div>
                <p style="font-size: 1rem; margin: 0;">稍等片刻，正在出卷...</p>
            </div>
        </div>
    `;
    document.body.appendChild(waitingModal);
}

// 显示等待弹窗
function showWaitingModal() {
    if (waitingModal) {
        waitingModal.classList.add('show');
    }
}

// 隐藏等待弹窗
function hideWaitingModal() {
    if (waitingModal) {
        waitingModal.classList.remove('show');
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initPage);
